import { login, getInfo, getDetailInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
// import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    // 用户信息
    userinof: null

  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  // 给用户信息赋值
  UserInfo: (state, info) => {
    state.userinof = info
  }
}

const actions = {
  // user login
  async login({ commit }, form) {
    const ret = await login({
      mobile: form.username,
      password: form.password
    })
    // console.log(ret.data.code)
    if (ret.code === 10000) {
      commit('SET_TOKEN', ret.data)
      setToken(ret.data)
      return Promise.resolve(true)
    } else {
      return Promise.reject(false)
    }
  },

  // 获取用户信息
  async getInfo({commit}) {
    const ret = await getInfo()
    const DetailInfo = await getDetailInfo(ret.data.userId)
    if (ret.code === 10000) {
      commit('UserInfo', {
        ...ret.data,
        ...DetailInfo.data
      })
    }
  },

  // 推出登录
  logout({ commit }) {
    // 清空token
    commit('SET_TOKEN', '')
    // 清空用户信息
    commit('UserInfo', '')
    // 删除token
    removeToken()
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
